<template>
    <el-tabs v-model="editableTabsValue" type="card" closable class="demo-tabs" @edit="handleTabsEdit"
        @tab-click="tabclick">
        <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
        </el-tab-pane>
    </el-tabs>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { TabPaneName, TabsPaneContext } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

let tabIndex = 1
const editableTabsValue = ref('1')
const editableTabs = ref([
    {
        title: '首页',
        name: '1',
        content: 'Tab 1 content',
    },
])

watch(route, (newval: any) => {
    handleTabsEdit(newval.name, 'add')
})

const tabclick = (pane: TabsPaneContext) => {
    // console.log(pane.props.label);
    router.push({ name: pane.props.label })
}

const handleTabsEdit = (
    targetName: TabPaneName | undefined,
    action: 'remove' | 'add'
) => {
    if (action === 'add') {
        let index = editableTabs.value.findIndex(v => v.title == targetName)

        if (index == -1) {
            const newTabName = `${++tabIndex}`
            editableTabs.value.push({
                title: targetName as string,
                name: newTabName,
                content: 'New Tab content',
            })
            editableTabsValue.value = newTabName
        } else {
            editableTabsValue.value = editableTabs.value[index].name
        }

    } else if (action === 'remove') {
        const tabs = editableTabs.value
        let activeName = editableTabsValue.value
        if (activeName === targetName) {
            tabs.forEach((tab, index) => {
                if (tab.name === targetName) {
                    const nextTab = tabs[index + 1] || tabs[index - 1]
                    if (nextTab) {
                        activeName = nextTab.name
                        router.push({ name: nextTab.title })
                    }
                }
            })
        }

        editableTabsValue.value = activeName
        editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
    }
}
</script>

<style>
.demo-tabs>.el-tabs__content {
    padding: 0px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}
</style>